import { useUserStore } from "@/stores/user";
import axios from "axios";
import router from "@/router";
import { ElMessage } from "element-plus";

const baseURL = "http://8.130.47.83:8090";

const instance = axios.create({
  baseURL,
  timeout: 100000,
  headers: { "Content-Type": "application/json;charset=UTF-8" },
  // withCredentials: true, // 允许携带cookie
});

instance.interceptors.request.use(
  (config) => {
    // const setCookie = res.headers["set-cookie"];
    // console.log(setCookie);

    return config;
  },
  (err) => Promise.reject(err)
);

instance.interceptors.response.use(
  (res) => {
    // 只检查响应中的data.code，而不是res.data.code
    // 根据控制台的请求信息，服务器返回的是200状态码
    const setCookie = res.headers["set-cookie"];
    console.log(setCookie);
    return res;
  },
  (err) => {
    // 网络错误或服务器错误处理
    const message = err.response?.data?.message || "网络连接异常";
    ElMessage({ message, type: "error" });

    if (err.response?.status === 401) {
      router.push("/login");
    }
    return Promise.reject(err);
  }
);

export default instance;
export { baseURL };
